package com.example.mr5.mygame.game2048;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Point;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.LinearLayout;
import android.widget.SimpleAdapter;
import android.widget.Toast;

import com.example.mr5.mygame.R;
import com.example.mr5.mygame.main.ad.AdAcitivty;
import com.example.mr5.mygame.utils.NetWorkConnection;
import com.example.mr5.mygame.utils.SharePreferenceUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Mr.5
 * Date：2016/5/8.
 * Time：14:19
 */
public class GameView extends LinearLayout {
    private static final int NumCostScore = 1;
    private static final int DeletiCarCostScore = 1;

    private Context context;
    NetWorkConnection conUtil = new NetWorkConnection(getContext());

    public GameView(Context context) {
        super(context);

        this.context = context;
        initGameView();
    }

    public GameView(Context context, AttributeSet attrs) {
        super(context, attrs);

        initGameView();
    }

    private void initGameView() {
        setOrientation(LinearLayout.VERTICAL);
        setBackgroundColor(0xffbbada0);


        setOnTouchListener(new OnTouchListener() {

            private float startX, startY, offsetX, offsetY;

            @Override
            public boolean onTouch(View v, MotionEvent event) {

                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
                        startX = event.getX();
                        startY = event.getY();
                        break;
                    case MotionEvent.ACTION_UP:
                        offsetX = event.getX() - startX;
                        offsetY = event.getY() - startY;


                        if (Math.abs(offsetX) > Math.abs(offsetY)) {
                            if (offsetX < -5) {
                                swipeLeft();
                            } else if (offsetX > 5) {
                                swipeRight();
                            }
                        } else {
                            if (offsetY < -5) {
                                swipeUp();
                            } else if (offsetY > 5) {
                                swipeDown();
                            }
                        }

                        break;
                }
                return true;
            }
        });
    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);
        Log.e("sceneWidth", w + "");
        Log.e("sceneHeight", h + "");

        Config.CARD_WIDTH = (Math.min(w, h) - 10) / Config.LINES;

        addCards(Config.CARD_WIDTH, Config.CARD_WIDTH);

        continueGame();
    }

    private void addCards(int cardWidth, int cardHeight) {

        Card c;

        LinearLayout line;
        LayoutParams lineLp;

        for (int y = 0; y < Config.LINES; y++) {
            line = new LinearLayout(getContext());
            lineLp = new LayoutParams(-1, cardHeight);
            addView(line, lineLp);

            for (int x = 0; x < Config.LINES; x++) {
                c = new Card(getContext());
                line.addView(c, cardWidth, cardHeight);

                cardsMap[x][y] = c;
            }
        }
    }

    public void startGame() {
        SharePreferenceUtil util = new SharePreferenceUtil(getContext());
        util.setBiggistNum(1024);
        Game2048Activity aty = Game2048Activity.getMainActivity();
        aty.clearScore();
        aty.showBestScore(aty.getBestScore());

        for (int y = 0; y < Config.LINES; y++) {
            for (int x = 0; x < Config.LINES; x++) {
                cardsMap[x][y].setNum(0);
            }
        }

        addRandomNum();
        addRandomNum();
    }

    public void continueGame() {
        Game2048Activity aty = Game2048Activity.getMainActivity();
        aty.showScore();
        aty.showBestScore(aty.getBestScore());

        if (aty.getMap() == "") {
            for (int y = 0; y < Config.LINES; y++) {
                for (int x = 0; x < Config.LINES; x++) {
                    cardsMap[x][y].setNum(0);
                }
            }
            addRandomNum();
            addRandomNum();
        } else {
            int k = 0;
            String[] map = aty.getMap().split("#");
            for (int x = 0; x < Config.LINES; x++) {
                for (int y = 0; y < Config.LINES; y++) {
                    cardsMap[x][y].setNum(Integer.parseInt(map[k++]));
                }
            }
        }
        checkComplete();

    }

    public void deleteCarAndContinue(int i, int j) {
        Game2048Activity aty = Game2048Activity.getMainActivity();
        aty.showBestScore(aty.getBestScore());
        cardsMap[i][j].setNum(0);
    }

    private void addRandomNum() {

        emptyPoints.clear();

        for (int y = 0; y < Config.LINES; y++) {
            for (int x = 0; x < Config.LINES; x++) {
                if (cardsMap[x][y].getNum() <= 0) {
                    emptyPoints.add(new Point(x, y));
                }
            }
        }

        if (emptyPoints.size() > 0) {

            Point p = emptyPoints.remove((int) (Math.random() * emptyPoints.size()));
            cardsMap[p.x][p.y].setNum(Math.random() > 0.1 ? 2 : 4);

            Game2048Activity.getMainActivity().getAnimLayer().createScaleTo1(cardsMap[p.x][p.y]);
        }
    }


    private void swipeLeft() {

        boolean merge = false;

        for (int y = 0; y < Config.LINES; y++) {
            for (int x = 0; x < Config.LINES; x++) {

                for (int x1 = x + 1; x1 < Config.LINES; x1++) {
                    if (cardsMap[x1][y].getNum() > 0) {

                        if (cardsMap[x][y].getNum() <= 0) {

                            Game2048Activity.getMainActivity().getAnimLayer().createMoveAnim(cardsMap[x1][y], cardsMap[x][y], x1, x, y, y);

                            cardsMap[x][y].setNum(cardsMap[x1][y].getNum());
                            cardsMap[x1][y].setNum(0);

                            x--;
                            merge = true;

                        } else if (cardsMap[x][y].equals(cardsMap[x1][y])) {
                            Game2048Activity.getMainActivity().getAnimLayer().createMoveAnim(cardsMap[x1][y], cardsMap[x][y], x1, x, y, y);
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
                            cardsMap[x1][y].setNum(0);

                            Game2048Activity.getMainActivity().addScore(cardsMap[x][y].getNum());
                            merge = true;
                        }

                        break;
                    }
                }
            }
        }

        if (merge) {
            checkBiggistNum();
            addRandomNum();
            checkComplete();
        }
    }

    private void swipeRight() {

        boolean merge = false;

        for (int y = 0; y < Config.LINES; y++) {
            for (int x = Config.LINES - 1; x >= 0; x--) {

                for (int x1 = x - 1; x1 >= 0; x1--) {
                    if (cardsMap[x1][y].getNum() > 0) {

                        if (cardsMap[x][y].getNum() <= 0) {
                            Game2048Activity.getMainActivity().getAnimLayer().createMoveAnim(cardsMap[x1][y], cardsMap[x][y], x1, x, y, y);
                            cardsMap[x][y].setNum(cardsMap[x1][y].getNum());
                            cardsMap[x1][y].setNum(0);

                            x++;
                            merge = true;
                        } else if (cardsMap[x][y].equals(cardsMap[x1][y])) {
                            Game2048Activity.getMainActivity().getAnimLayer().createMoveAnim(cardsMap[x1][y], cardsMap[x][y], x1, x, y, y);
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
                            cardsMap[x1][y].setNum(0);
                            Game2048Activity.getMainActivity().addScore(cardsMap[x][y].getNum());
                            merge = true;
                        }

                        break;
                    }
                }
            }
        }

        if (merge) {
            checkBiggistNum();
            addRandomNum();
            checkComplete();
        }
    }

    private void swipeUp() {

        boolean merge = false;

        for (int x = 0; x < Config.LINES; x++) {
            for (int y = 0; y < Config.LINES; y++) {

                for (int y1 = y + 1; y1 < Config.LINES; y1++) {
                    if (cardsMap[x][y1].getNum() > 0) {

                        if (cardsMap[x][y].getNum() <= 0) {
                            Game2048Activity.getMainActivity().getAnimLayer().createMoveAnim(cardsMap[x][y1], cardsMap[x][y], x, x, y1, y);
                            cardsMap[x][y].setNum(cardsMap[x][y1].getNum());
                            cardsMap[x][y1].setNum(0);

                            y--;

                            merge = true;
                        } else if (cardsMap[x][y].equals(cardsMap[x][y1])) {
                            Game2048Activity.getMainActivity().getAnimLayer().createMoveAnim(cardsMap[x][y1], cardsMap[x][y], x, x, y1, y);
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
                            cardsMap[x][y1].setNum(0);
                            Game2048Activity.getMainActivity().addScore(cardsMap[x][y].getNum());
                            merge = true;
                        }

                        break;

                    }
                }
            }
        }

        if (merge) {
            checkBiggistNum();
            addRandomNum();
            checkComplete();
        }
    }

    private void swipeDown() {

        boolean merge = false;

        for (int x = 0; x < Config.LINES; x++) {
            for (int y = Config.LINES - 1; y >= 0; y--) {

                for (int y1 = y - 1; y1 >= 0; y1--) {
                    if (cardsMap[x][y1].getNum() > 0) {

                        if (cardsMap[x][y].getNum() <= 0) {
                            Game2048Activity.getMainActivity().getAnimLayer().createMoveAnim(cardsMap[x][y1], cardsMap[x][y], x, x, y1, y);
                            cardsMap[x][y].setNum(cardsMap[x][y1].getNum());
                            cardsMap[x][y1].setNum(0);

                            y++;
                            merge = true;
                        } else if (cardsMap[x][y].equals(cardsMap[x][y1])) {
                            Game2048Activity.getMainActivity().getAnimLayer().createMoveAnim(cardsMap[x][y1], cardsMap[x][y], x, x, y1, y);
                            cardsMap[x][y].setNum(cardsMap[x][y].getNum() * 2);
                            cardsMap[x][y1].setNum(0);
                            Game2048Activity.getMainActivity().addScore(cardsMap[x][y].getNum());
                            merge = true;
                        }

                        break;
                    }
                }
            }
        }

        if (merge) {
            checkBiggistNum();
            addRandomNum();
            checkComplete();
        }
    }

    private void checkBiggistNum() {
        int biggistNum = 0;
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                if (cardsMap[i][j].getNum() > biggistNum) {
                    biggistNum = cardsMap[i][j].getNum();
                }
            }
        }
        SharePreferenceUtil util = new SharePreferenceUtil(getContext());
        if ((biggistNum == util.getBiggistNum())&&(util.getShowAd().equals("yes"))) {
            new AlertDialog.Builder(getContext()).setTitle("你好")
                    .setMessage("您已达到" + biggistNum + "，继续游戏需消耗"+Integer.parseInt(util.getCostScore1()) +"积分")
                    .setPositiveButton("继续",
                            new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {
                                    if (conUtil.isConnection()) {
                                        SharePreferenceUtil util = new SharePreferenceUtil(getContext());
                                        if (util.getScore() >= Integer.parseInt(util.getCostScore1())) {
                                            util.setScore(util.getScore() - Integer.parseInt(util.getCostScore1()));
                                            Game2048Activity.getMainActivity().costScore(Integer.parseInt(util.getCostScore1()));
                                            util.setBiggistNum(2 * util.getBiggistNum());
                                        } else {
                                            new AlertDialog.Builder(getContext()).setTitle("你好")
                                                    .setMessage("您当前积分不足，是否前往赚取积分？")
                                                    .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                                        @Override
                                                        public void onClick(DialogInterface dialog, int which) {
                                                            Game2048Activity.getMainActivity().gotoEarnScore();                                                        }
                                                    }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                                                @Override
                                                public void onClick(DialogInterface dialog, int which) {
                                                    ((Activity) getContext()).finish();
                                                }
                                            }).show();
                                        }
                                    } else
                                        Toast.makeText(getContext(), "请检查网络连接", Toast.LENGTH_LONG).show();
                                }
                            }

                    ).setNegativeButton("退出", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            ((Activity) getContext()).finish();
                        }
                    }

            ).show();
        }
    }

    private void checkComplete() {

        boolean complete = true;

        ALL:
        for (int y = 0; y < Config.LINES; y++) {
            for (int x = 0; x < Config.LINES; x++) {
                if (cardsMap[x][y].getNum() == 0 ||
                        (x > 0 && cardsMap[x][y].equals(cardsMap[x - 1][y])) ||
                        (x < Config.LINES - 1 && cardsMap[x][y].equals(cardsMap[x + 1][y])) ||
                        (y > 0 && cardsMap[x][y].equals(cardsMap[x][y - 1])) ||
                        (y < Config.LINES - 1 && cardsMap[x][y].equals(cardsMap[x][y + 1]))) {

                    complete = false;
                    break ALL;
                }
            }
        }

        if (complete) {
            SharePreferenceUtil util = new SharePreferenceUtil(getContext());

            if(util.getShowAd().equals("yes")){
                new AlertDialog.Builder(getContext()).setTitle("你好").setMessage("游戏结束，是否消耗" + Integer.parseInt(util.getCostScore2()) + "积分消除任意一个卡片？")
                        .setPositiveButton("是", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {

                                if (conUtil.isConnection()) {
                                    SharePreferenceUtil util = new SharePreferenceUtil(getContext());
                                    if (util.getScore() >= Integer.parseInt(util.getCostScore2()) ) {
                                        util.setScore(util.getScore() - Integer.parseInt(util.getCostScore2()) );
                                        Game2048Activity.getMainActivity().costScore(Integer.parseInt(util.getCostScore2()) );

                                        final AlertDialog alertDialog = new AlertDialog.Builder(getContext()).create();
                                        alertDialog.show();
                                        Window window = alertDialog.getWindow();
                                        window.setContentView(R.layout.dialog_gridview);
                                        GridView gridView = (GridView) window.findViewById(R.id.dialog_gridview);
                                        gridView.setAdapter(new ArrayAdapter<Integer>(getContext(), R.layout.item_card_gridview, getData()));
                                        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                                            @Override
                                            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                                                deleteCarAndContinue(position % 4, position / 4);
                                                alertDialog.dismiss();
                                            }
                                        });
                                    } else {
                                        new AlertDialog.Builder(getContext()).setTitle("你好")
                                                .setMessage("您当前积分不足，是否前往赚取积分？")
                                                .setPositiveButton("是", new DialogInterface.OnClickListener() {
                                                    @Override
                                                    public void onClick(DialogInterface dialog, int which) {
                                                        Game2048Activity.getMainActivity().gotoEarnScore();
                                                    }
                                                }).setNegativeButton("否", new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {
                                                ((Activity) getContext()).finish();
                                            }
                                        }).show();
                                    }
                                } else
                                    Toast.makeText(getContext(), "请检查网络连接", Toast.LENGTH_LONG).show();
                            }
                        }).setNegativeButton("重新开始", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        startGame();
                    }
                }).show();
            }else {
                new AlertDialog.Builder(getContext()).setTitle("你好")
                        .setMessage("游戏结束")
                        .setPositiveButton("重新开始", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                startGame();
                            }
                        }).show();
            }

        }

    }

    public List<Integer> getData() {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 0; i < 4; i++) {
            for (int j = 0; j < 4; j++) {
                list.add(cardsMap[j][i].getNum());
            }
        }
        return list;

    }

    public String getMap() {
        String map = "";
        for (int i = 0; i < Config.LINES; i++) {
            for (int j = 0; j < Config.LINES; j++) {
                map += (cardsMap[i][j].getNum() + "#");
            }
        }
        return map;
    }

    private Card[][] cardsMap = new Card[Config.LINES][Config.LINES];
    private List<Point> emptyPoints = new ArrayList<Point>();
}
